//
//  BRReportStillRunViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/10/8.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//  上报归还后，订单还在运行的问题。

#import "BRReportStillRunViewController.h"
#import "BROderReportViewController.h"
#import "BRCanRentModel.h"
#import "BRInCabinetViewController.h"
#import "BRAnimationView.h"
#import "BROrderDetailViewController.h"

#define WaitingTime 100///等待时长
#define AnimatedTime 2.08///动效时长

@interface BRReportStillRunViewController ()
{
    QMUIButton *_confirmBtn;
    QMUILabel *_titleL;
    UIImageView *_bigImg;
    UIImageView *_lampImg1;
    UIImageView *_lampImg2;
    UIImageView *_lampImg3;
}

@property (nonatomic,assign) BOOL isRunning;

@property (nonatomic,strong) BRAnimationView *animationImg;
//@property (nonatomic, strong) dispatch_source_t timerWait;//等待时长
@property (nonatomic, strong) dispatch_source_t timerOrder;//轮训订单
//@property (nonatomic, strong) dispatch_source_t timer2;//动效时长

@end

@implementation BRReportStillRunViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUI];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}

- (void)dealloc {
    //NSLog(@"进度条页面销毁 \n");
    [self cancelAllTimer];
}

- (void)cancelAllTimer {
    
    [self.animationImg stop];
    
    if (self.timerOrder) {
        dispatch_source_cancel(self.timerOrder);
        self.timerOrder = nil;
    }

}

#pragma mark - Request --
- (void)quryOrder {
    /*
     
     isInCabinet": true,是否在机柜，true:在 false：不在
             "isPay": true,是否需要支付，true:需要 false：不需要
             "msgCode": "",短信验证码
             "orderNo": "",订单号
             "payMoney": 0,需支付的金额
             "rentOrNot": 0,0:可以租借 1：没有绑定银行卡 2：有未支付订单 3：子账号有未完成订单 4：租借订单已达上限 5：绑定的卡还有即将过期 6:主账号有未支付订单 7:主账号绑定的卡过期或异常状态 8：主账号绑定的卡即将过期 9:调查中的订单已达到上限
     */
    [[BRRequestManager shared] GET:[BRAPI checkOrder:self.orderNo] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {


        NSLog(@"进来了 == %@",dataDict);
        NSDictionary *dataDic = dataDict[@"data"];
        if (BR_DictIsEmpty(dataDic)) {
            return;
        }
        self.isRunning = NO;
        BRCanRentModel *model = [BRCanRentModel mj_objectWithKeyValues:dataDict[@"data"]];
        
        [self showHUD:(model.isInCabinet == 1)];

    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        self.isRunning = NO;
    }];
}

- (void)showHUD:(BOOL)inset {
    
    NSString *text = Localized(@"home_unfindPB");
    NSString *btnL = Localized(@"home_recheck");
    NSString *btnR = Localized(@"home_reportIssue");
    
    if (inset) {
        text = Localized(@"home_pbFoundResult");
        btnL = Localized(@"order_homePage");
        btnR = Localized(@"home_viewOrder");
    }
    
    WS(weakSelf);
    BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:text subTitle:@"" cancelStr:btnL succStr:btnR cancelAction:^{
        if (inset) {
            [weakSelf popHome];
        }else {
            [weakSelf checkOrder];
        }
        
    } successAction:^{
        if (inset) {
            [weakSelf toOrderDetail];
        }else {
            [weakSelf reportIssue];
        }
        
    } showBC:YES];
    
    [self.view addSubview:alertV];
}

- (void)toOrderDetail {
    BROrderDetailViewController *deVC = [[BROrderDetailViewController alloc] init];
    deVC.orderNo = self.orderNo;
    deVC.popType = 1;
    [self.navigationController pushViewController:deVC animated:YES];
    
}

- (void)reportIssue {
    BROderReportViewController *vc = [BROderReportViewController new];
    vc.vcType = Report_NoInset;
    vc.orderNo = self.orderNo;
    vc.orderType = self.orderType;
    vc.maxAmount = self.dto.billing.penaltyAmount;
    [self.navigationController pushViewController:vc animated:YES];
   
}
- (void)popHome {
    
    [self pop];
}
- (void)recheckOrder {
    
    [self checkOrder];
}


#pragma mark - ACTION --
- (void)checkOrder {
    
    self.isRunning = YES;
    
    [self run];
    WS(weakSelf);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf startTimeOrder];
    });

}

- (void)setIsRunning:(BOOL)isRunning {
    _isRunning = isRunning;
    
    [self.navView br_hiddenLBtn:isRunning];
    _confirmBtn.hidden = isRunning;
    if (!isRunning) {
        // 结束定时轮巡
        [self cancelAllTimer];
    }
    
    [self br_resetTitle];
}

//- (void)toReportVC {
//    BROderReportViewController *vc = [[BROderReportViewController alloc] init];
//    vc.orderType = self.orderType;
//    vc.vcType = Report_NoInset;
//    [self.navigationController pushViewController:vc animated:YES];
//}

- (void)animateView:(UIImageView *)animateV time:(CGFloat)time alpha:(CGFloat)alpha completion:(void(^)(BOOL finished))completion {
    
    [UIView animateWithDuration:time animations:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [animateV setAlpha:alpha];
        });
    } completion:completion];
}

- (void)run {
    
    [self.animationImg start];
//    [self runAnimate:^(BOOL finished) {
//
//    }];
}


- (void)runAnimate:(void(^)(BOOL finished))completion {
    
    if (!self.isRunning) return;
    
    [UIView animateWithDuration:0.6 animations:^{
        self->_lampImg2.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
    [UIView  animateWithDuration:0.7 animations:^{
        self->_lampImg1.alpha = 0;
        
    } completion:^(BOOL finished) {
        [self runAnimate2:^(BOOL finished) {

        }];
    }];
    
}

- (void)runAnimate2:(void(^)(BOOL finished))completion {
    if (!self.isRunning) return;
    [UIView animateWithDuration:0.6 animations:^{
        self->_lampImg3.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
    [UIView  animateWithDuration:0.7 animations:^{
        self->_lampImg2.alpha = 0;
//        self->_lampImg3.alpha = 1;
    } completion:^(BOOL finished) {
        [self runAnimate3:^(BOOL finished) {

        }];
    }];
    
    
}
- (void)runAnimate3:(void(^)(BOOL finished))completion {
    
    if (!self.isRunning) return;
    [UIView animateWithDuration:0.6 animations:^{
        self->_lampImg1.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
    [UIView  animateWithDuration:0.7 animations:^{
        self->_lampImg3.alpha = 0;
//        self->_lampImg1.alpha = 1;
    } completion:^(BOOL finished) {
        [self runAnimate:^(BOOL finished) {

        }];
    }];
    
}

#pragma mark - 定时器
///动效时长中进度条定时器
-(void)startTime2 {
    __weak __typeof__(self) weakSelf = self;
//    __block double progressNum1 = 0; //进度条时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
//    self.timer2 = _timer;
    NSTimeInterval duration = 2.1;//每秒执行
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0), duration * NSEC_PER_SEC, 0);
    
    dispatch_source_set_event_handler(_timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf run];
        });
        
//        NSLog(@"%@",[NSDate date]);
//        if(progressNum1 > AnimatedTime){ //等待倒计时结束，关闭
//            if (_timer) {
//                dispatch_source_cancel(_timer);
//            }
//        }else{
//            NSString *strTime = [NSString stringWithFormat:@"%.0lf%%", (100*progressNum1)/AnimatedTime];
//            dispatch_async(dispatch_get_main_queue(), ^{
////                weakSelf.progressLabel.text = strTime;
//                //动效停留
//                if (progressNum1 > 1.12 && progressNum1 < 1.90) {
////                    weakSelf.progressLabel.text = @"60%";
//                }
//            });
//            progressNum1 += duration;
//        }
    });

    dispatch_resume(_timer);
}

///等待时长中进度条定时器
-(void)startTimeWait {
    __weak __typeof__(self) weakSelf = self;
    __block int progressNum1 = 0; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
//    self.timerWait = _timer;
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0), 1 * NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        if(progressNum1 > WaitingTime){ //倒计时结束，关闭
            [self cancelAllTimer];
            dispatch_async(dispatch_get_main_queue(), ^{
//                [HUD showHUDWithText:[NSString stringWithFormat:@"%@",Localized(@"RentPro_Page_Failed")]];
//                [self didBackButton];
            });
        }else{
            /*
            NSString *strTime = [NSString stringWithFormat:@"%d%%", progressNum1];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                weakSelf.progressLabel.text = strTime;
            });
            */
            ///移用了动效定时器
            progressNum1 ++;
        }
    });
    
    dispatch_resume(_timer);
}

///轮训订单定时器
-(void)startTimeOrder {
    __weak __typeof__(self) weakSelf = self;
    __block int progressNum = 0; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    self.timerOrder = _timer;
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0), 5 * NSEC_PER_SEC, 0); //每秒执行
    
    int down = WaitingTime/5;
    dispatch_source_set_event_handler(_timer, ^{
        if(progressNum > down){ //倒计时结束，关闭 (11)
            if (_timer) {
                dispatch_source_cancel(_timer);
            }
            [weakSelf.animationImg stop];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf quryOrder];
            });
            progressNum ++;
        }
    });
    
    dispatch_resume(_timer);
    
}

- (void)br_resetTitle {
    NSString *title = Localized(@"home_failedEject");
    NSString *text =  Localized(@"home_confirmPBNotEject");
    
    if (self.orderType == 2) {
        title = Localized(@"home_orderDidNotEnd");
        text =  Localized(@"home_confirmPBIn");
    }
    
    if (self.isRunning) {
        title = Localized(@"home_searchingPB");
        text =  Localized(@"home_searchingPBText");
    }
    
    self.navView.titleL.text = title;
    _titleL.text = text;
    
}


#pragma mark - SET UI --
- (void)setUI {
    
//    NSString *title = Localized(@"home_failedEject");
    NSString *btnStr = Localized(@"home_confirm");
//    NSString *text =  Localized(@"home_confirmPBNotEject");
    
    if (self.orderType == 2) {
//        title = Localized(@"home_orderDidNotEnd");
        btnStr = Localized(@"home_confirm");
//        text =  Localized(@"home_confirmPBIn");
    }
    
    [self br_createTop:@"--"];

//
    QMUIButton *submitBtn = [BRToolsView br_btnBGImg:btnStr];
    submitBtn.layer.masksToBounds = YES;
    submitBtn.titleLabel.font = [UIFont fontB:17];
    [self.view addSubview:submitBtn];
    [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
        make.width.mas_equalTo(kScreenWidth - 28);
        make.centerX.equalTo(self.view);
        make.bottom.offset(-(14 + kSafeAreaBottomHeight));
    }];
    [submitBtn addTarget:self action:@selector(checkOrder) forControlEvents:UIControlEventTouchUpInside];
    _confirmBtn = submitBtn;
    
    [self.view addSubview:self.animationImg];
    [self.animationImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(141);
        make.height.mas_equalTo(141);
        make.top.offset(28 + kSafeAreaTopHeight);
        make.centerX.equalTo(self.view);
    }];
    
//
    QMUILabel *titleL = [[QMUILabel alloc] init];
    titleL.textAlignment = NSTextAlignmentCenter;
    titleL.textColor = kColorTitle889;
    titleL.text = @"";
    titleL.font = [UIFont fontS:17];
    titleL.numberOfLines = 0;
    [self.view addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(kMarginLR2);
        make.right.equalTo(self.view).offset(-kMarginLR2);
        make.top.equalTo(self.animationImg.mas_bottom).offset(0);
    }];
    _titleL = titleL;
    
    [self br_resetTitle];
}

- (BRAnimationView *)animationImg {
    
    if (_animationImg == nil) {
        
        _animationImg = [[BRAnimationView alloc] init];
        _animationImg.defaultImg = UIImageMake(@"faq_warning");
        _animationImg.image = UIImageMake(@"faq_warning");
    }
    return _animationImg;
}

- (BOOL)forceEnableInteractivePopGestureRecognizer {
    // 屏蔽右滑返回
    return !self.isRunning;

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
